package com.example.redis.service;

import com.example.entity.Product;
import com.example.entity.User;
import com.example.redis.util.CacheKeyGenerator;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Map类型参数查询服务
 * 演示如何使用Map参数进行缓存查询
 *
 * @author example
 */
@Service
public class MapQueryService {

    // 模拟数据库数据
    private final List<User> userDatabase = Arrays.asList(
            new User(1L, "张三", "zhangsan@example.com", "13800138001", 25, "北京市朝阳区"),
            new User(2L, "李四", "lisi@example.com", "13800138002", 30, "上海市浦东新区"),
            new User(3L, "王五", "wangwu@example.com", "13800138003", 28, "广州市天河区"),
            new User(4L, "赵六", "zhaoliu@example.com", "13800138004", 35, "深圳市南山区")
    );

    private final List<Product> productDatabase = Arrays.asList(
            new Product(1L, "iPhone 15", "苹果最新手机", new BigDecimal("5999.0"), 100, "手机", Arrays.asList("苹果", "智能手机")),
            new Product(2L, "MacBook Pro", "专业级笔记本电脑", new BigDecimal("12999.0"), 50, "电脑", Arrays.asList("苹果", "笔记本")),
            new Product(3L, "华为 Mate 60", "华为旗舰手机", new BigDecimal("6999.0"), 80, "手机", Arrays.asList("华为", "智能手机")),
            new Product(4L, "小米 14", "小米旗舰手机", new BigDecimal("3999.0"), 120, "手机", Arrays.asList("小米", "智能手机"))
    );

    /**
     * 根据Map参数查询用户列表
     * 使用自定义缓存键生成器
     */
    @Cacheable(value = "userQuery", keyGenerator = "cacheKeyGenerator")
    public List<User> queryUsersByMap(Map<String, Object> queryParams) {
        // 模拟数据库查询延迟
        try {
            System.out.println("模拟查询数据库开始");
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        return userDatabase.stream()
                .filter(user -> {
                    // 根据Map中的条件过滤用户
                    if (queryParams.containsKey("minAge")) {
                        Integer minAge = (Integer) queryParams.get("minAge");
                        if (user.getAge() < minAge) return false;
                    }
                    if (queryParams.containsKey("maxAge")) {
                        Integer maxAge = (Integer) queryParams.get("maxAge");
                        if (user.getAge() > maxAge) return false;
                    }
                    if (queryParams.containsKey("city")) {
                        String city = (String) queryParams.get("city");
                        if (!user.getAddress().contains(city)) return false;
                    }
                    if (queryParams.containsKey("keyword")) {
                        String keyword = (String) queryParams.get("keyword");
                        if (!user.getUsername().contains(keyword) && !user.getEmail().contains(keyword)) {
                            return false;
                        }
                    }
                    return true;
                })
                .collect(Collectors.toList());
    }

    /**
     * 根据Map参数查询产品列表
     * 使用SpEL表达式生成缓存键
     */
    @Cacheable(value = "productQuery", key = "'queryProductsByMap:' + #queryParams.toString()")
    public List<Product> queryProductsByMap(Map<String, Object> queryParams) {
        // 模拟数据库查询延迟
        try {
            System.out.println("开始数据库查询");
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        return productDatabase.stream()
                .filter(product -> {
                    // 根据Map中的条件过滤产品
                    if (queryParams.containsKey("minPrice")) {
                        Double minPrice = (Double) queryParams.get("minPrice");
                        if (product.getPrice().equals(minPrice)) return false;
                    }
                    if (queryParams.containsKey("maxPrice")) {
                        Double maxPrice = (Double) queryParams.get("maxPrice");
                        if (maxPrice.equals(product.getPrice())) return false;
                    }
                    if (queryParams.containsKey("category")) {
                        String category = (String) queryParams.get("category");
                        if (!product.getCategory().equals(category)) return false;
                    }
                    if (queryParams.containsKey("keyword")) {
                        String keyword = (String) queryParams.get("keyword");
                        if (!product.getName().contains(keyword) && !product.getDescription().contains(keyword)) {
                            return false;
                        }
                    }
                    if (queryParams.containsKey("tags")) {
                        @SuppressWarnings("unchecked")
                        List<String> tags = (List<String>) queryParams.get("tags");
                        if (tags != null && !tags.isEmpty()) {
                            boolean hasTag = tags.stream().anyMatch(tag -> product.getTags().contains(tag));
                            if (!hasTag) return false;
                        }
                    }
                    return true;
                })
                .collect(Collectors.toList());
    }

    /**
     * 复杂查询：根据多个Map参数进行分页查询
     * 使用手动生成的缓存键
     */
    @Cacheable(value = "complexQuery", key = "#root.target.generateComplexKey(#queryParams, #pageParams)")
    public Map<String, Object> complexQuery(Map<String, Object> queryParams, Map<String, Object> pageParams) {
        // 模拟数据库查询延迟
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        // 获取分页参数
        Integer pageNum = (Integer) pageParams.getOrDefault("pageNum", 1);
        Integer pageSize = (Integer) pageParams.getOrDefault("pageSize", 10);

        // 执行查询逻辑
        List<User> users = queryUsersByMap(queryParams);
        List<Product> products = queryProductsByMap(queryParams);

        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("users", users);
        result.put("products", products);
        result.put("total", users.size() + products.size());
        result.put("pageNum", pageNum);
        result.put("pageSize", pageSize);

        return result;
    }

    /**
     * 生成复杂查询的缓存键
     * 这个方法会被SpEL表达式调用
     */
    public String generateComplexKey(Map<String, Object> queryParams, Map<String, Object> pageParams) {
        return CacheKeyGenerator.generateMapKeyWithPrefix("complex", "complexQuery",
                mergeMaps(queryParams, pageParams));
    }

    /**
     * 合并两个Map
     */
    private Map<String, Object> mergeMaps(Map<String, Object> map1, Map<String, Object> map2) {
        Map<String, Object> merged = new HashMap<>();
        if (map1 != null) merged.putAll(map1);
        if (map2 != null) merged.putAll(map2);
        return merged;
    }

    /**
     * 手动缓存示例：使用RedisTemplate直接操作缓存
     */
    public List<User> queryUsersWithManualCache(Map<String, Object> queryParams) {
        // 生成缓存键
        String cacheKey = CacheKeyGenerator.generateMapKey("manualUserQuery", queryParams);

        // 这里可以注入RedisTemplate来手动操作缓存
        // 示例代码：
        // @Autowired private RedisTemplate<String, Object> redisTemplate;
        // List<User> cachedResult = (List<User>) redisTemplate.opsForValue().get(cacheKey);
        // if (cachedResult != null) {
        //     return cachedResult;
        // }

        // 执行查询
        List<User> result = queryUsersByMap(queryParams);

        // 手动设置缓存
        // redisTemplate.opsForValue().set(cacheKey, result, 1, TimeUnit.HOURS);

        return result;
    }
}
